<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <button class="btn5">点击启动到500</button>
    <button class="btn8">点击启动到800</button>
    <div>

    </div>
    <script>
        var div = document.querySelector('div');
        var btn5 = document.querySelector('.btn5');
        var btn8 = document.querySelector('.btn8');
        function animate(obj, target, callback) {
            clearInterval(obj.timer);
            var timer = setInterval(function () {
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft == target) {
                    clearInterval(timer);
                    if (callback) {
                        callback();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 15)
        }
        btn5.addEventListener('click', function () {
            animate(div, 500);
        });
        btn8.addEventListener('click', function () {
            animate(div, 800, function () {
                div.style.backgroundColor = 'red';
            });
        })
    </script>
</body>

</html>